14. AsyncTask Generic Params in Quake Report App

AsyncTask Generic Parameters in Quake Report App

Question:

Start Quiz:

Solution:

List vs ArrayList

So lately we've seen a lot of usage of List and ArrayList. They both appear to be used in a similar way -- so what's the difference here?

The fundamental difference here is pretty simple: List is an interface, whereas ArrayList is a concrete class. You CANNOT create an object instance of List because it’s an interface and its methods are not implemented. However, you CAN create an object instance of ArrayList and specify a generic parameter for E, because it is a concrete class.

For example: To define an instance of an ArrayList using the Earthquake data type, you could write:

  ArrayList<Earthquake> earthquakeList = new ArrayList<Earthquake>();

That would work fine. However, you can also store that object in a variable of data type List:

  List<Earthquake> earthquakeList = new ArrayList<Earthquake>();

The reason why you'd ever want to do such a thing is for flexibility:

Another similar type of class to ArrayList is LinkedList, which also implements the List interface. Both classes have similar methods and implementation strategies, but somewhat different internal details and memory implications. If for some reason your app would benefit from using LinkedList instead of ArrayList, then it would be easy to just update the instance where it is defined, and then all of your List code should still work! Here's an example:

  List<Earthquake> earthquakeList = new ArrayList<Earthquake>();
  earthquakeList.add(foo);

Becomes:

  List<Earthquake> earthquakeList = new LinkedList<Earthquake>();
  earthquakeList.add(foo);

And it still works!

In all cases, the best practice is to use List whenever you need a list object (whether ArrayList or LinkedList), so you can keep your code flexible.

To learn more about this, please read the documentation for the List interface, and check out these great discussions on StackOverflow on when to use List and when you might use ArrayList vs. LinkedList.